package main

import (
	"database/sql"
	"fmt"
	"net/http"
	"text/template"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func initDB() (err error) {
	dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True"
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		return err
	}
	// 尝试与数据库建立连接（校验dsn是否正确）
	err = db.Ping()
	if err != nil {
		return err
	}
	return nil
}

type User struct {
	Id   int
	Age  int
	Name string
}

// 查询单条数据示例
func queryRowDemo(id int) User {
	var u User
	sqlStr := "select id, name, age from user where id=?"
	// 非常重要：确保QueryRow之后调用Scan方法，否则持有的数据库链接不会被释放
	err := db.QueryRow(sqlStr, id).Scan(&u.Id, &u.Name, &u.Age)
	if err != nil {
		fmt.Printf("scan failed, err:%v\n", err)
		return u
	}
	fmt.Printf("id:%d name:%s age:%d\n", u.Id, u.Name, u.Age)
	return u
}

func sayHello(w http.ResponseWriter, r *http.Request) {

	tmpl, err := template.ParseFiles("./tmpl/hello.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	s := queryRowDemo(1)
	fmt.Printf("id2:%d name2:%s age2:%d\n", s.Id, s.Name, s.Age)
	tmpl.Execute(w, s)
}

func main() {
	err := initDB()
	if err != nil {
		fmt.Println("init db failed,err ", err)
		return
	}

	http.HandleFunc("/", sayHello)
	err1 := http.ListenAndServe(":9090", nil)
	if err1 != nil {
		fmt.Println("HTTP server failed,err:", err1)
		return
	}
}
